package com.simplecontact.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.simplecontact.R;
import com.simplecontact.adapters.adSimpleText;
import com.simplecontact.classes.Contact;
import com.simplecontact.classes.GroupContact;
import com.simplecontact.classes.Groups;
import com.simplecontact.utils.Utils;

public class ActGroup extends Activity {
	private ListView lsv2;
	
	protected void onStart ()
	{
		super.onStart();
		lsv2 = (ListView)findViewById(R.id.listview2);							
		String[] arrName = getGroupName();
		int[] arrId = getGroupId();
		if(arrId!=null)
			lsv2.setAdapter(new adSimpleText(getApplicationContext(), arrName, arrId));
		else
			lsv2.setAdapter(null);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.group);        
        lsv2 = (ListView)findViewById(R.id.listview2);						
		String[] arrName = getGroupName();
		int[] arrId = getGroupId();
		if(arrId!=null)
			lsv2.setAdapter(new adSimpleText(getApplicationContext(), arrName, arrId));
	}
	@Override
    public boolean onPrepareOptionsMenu (Menu menu){
    	menu.clear();
    	menu.add(0, Utils.MENU_ADD_GROUP, 0, getString(R.string.strAdd)).setIcon(R.drawable.group_add);
    	menu.add(0, Utils.MENU_EDIT_GROUP, 1, getString(R.string.strEdit)).setIcon(R.drawable.group_edit);
    	menu.add(0, Utils.MENU_DELETE_GROUP, 2, getString(R.string.strDelete)).setIcon(R.drawable.group_delete);
    	menu.add(0, Utils.MENU_VIEW_CONTACT, 3, getString(R.string.strViewContact)).setIcon(R.drawable.tabmember);
    	menu.add(0, Utils.MENU_GROUP_CHAT, 4, getString(R.string.strChat)).setIcon(R.drawable.chat);
		return true;
	}
	 @Override
	 public boolean onOptionsItemSelected(MenuItem item) {    
    	// Handle item selection    
    	switch (item.getItemId()) {
    	case Utils.MENU_ADD_GROUP:    	
			prepareToInsertGroup(ActGroup.this, R.layout.group_dialog, R.id.edgroupname, R.id.btnDone, R.id.btnRevert, getString(R.string.strGroupName), "").show();
			return true;    		 
		case Utils.MENU_EDIT_GROUP:
			if(lsv2 != null){
				if(lsv2.getSelectedItemId()>-1){
					Cursor c = getContentResolver().query(Groups.GroupColumns.CONTENT_URI, null, " _id=" + lsv2.getSelectedItemId(), null, null);				
			        if (c.moveToFirst()) {        	    										
						int column = c.getColumnIndex(Groups.GroupColumns.GROUPNAME);    						    						
						prepareToEditGroup(ActGroup.this, R.layout.group_dialog, R.id.edgroupname, R.id.btnDone, R.id.btnRevert, getString(R.string.strGroupName), c.getString(column)).show();
					}    							
				}
				else{
					Toast.makeText(this, getString(R.string.strChooseToEdit), Toast.LENGTH_SHORT).show();
				}
			}    			
			return true;    		 
		case Utils.MENU_DELETE_GROUP:
			if(lsv2 != null){
				if(lsv2.getSelectedItemId()>-1){
					deleteGroupContact((int)ActContact.lsv1.getSelectedItemId(), GroupContact.GroupContactColumns.GROUPID);
					deleteGroup((int)lsv2.getSelectedItemId());
				}
				else{
					Toast.makeText(this, getString(R.string.strChooseToDelete), Toast.LENGTH_SHORT).show();
				}
			}
			return true;    	
		case Utils.MENU_VIEW_CONTACT:
			if(lsv2 != null){
				if(lsv2.getSelectedItemId()>-1){
					ActContact.idgroup = (int) lsv2.getSelectedItemId(); 
					ActMain.mTabHost.setCurrentTab(0);				
				}
			}
			else{
				Toast.makeText(this, getString(R.string.strChooseToView), Toast.LENGTH_SHORT).show();
			}
			return true;
		case Utils.MENU_GROUP_CHAT:
			if(lsv2 != null){
				if(lsv2.getSelectedItemId()>-1){
					Cursor c = getContentResolver().query(GroupContact.GroupContactColumns.CONTENT_URI, new String[]{GroupContact.GroupContactColumns.CONTACTID}, GroupContact.GroupContactColumns.GROUPID + "=" + lsv2.getSelectedItemId(), null, null);
					if (c.moveToFirst()) {
						ArrayList<String> arrPhone = new ArrayList<String>();
						ArrayList<String> arrNick = new ArrayList<String>();
						ArrayList<String> arrPic = new ArrayList<String>();
						int ColumnFisrt = c.getColumnIndex(GroupContact.GroupContactColumns.CONTACTID);
						do {
							// Get the field values								
							int i = c.getInt(ColumnFisrt);
							Cursor c1 = getContentResolver().query(Contact.ContactColumns.CONTENT_URI, null, Contact.ContactColumns._ID + "=" + i, null, null);
							if (c1.moveToFirst()) {
								int Column = c1.getColumnIndex(Contact.ContactColumns.PHONENUMBER);    
	    						int Column1 = c1.getColumnIndex(Contact.ContactColumns.NICKNAME);
	    						int Column2 = c1.getColumnIndex(Contact.ContactColumns.IMAGE);								
								do {
									arrPhone.add(c1.getString(Column));
									arrNick.add(c1.getString(Column1));
									arrPic.add(c1.getString(Column2));
								} while (c1.moveToNext());
							}							
						} while (c.moveToNext());
						String[] _arrPhone = new String[arrPhone.size()];
						String[] _arrNick = new String[arrNick.size()];
						String[] _arrPic = new String[arrPic.size()];
						for(int i = 0 ; i < arrPhone.size() ; i++){
							_arrPhone[i] = arrPhone.get(i);
							_arrNick[i] = arrNick.get(i);
							_arrPic[i] = arrPic.get(i);
						}
						startActivity(new Intent(ActGroup.this, ActChat.class).putExtra("arrPhone", _arrPhone).putExtra("arrNick", _arrNick).putExtra("arrPic", _arrPic));
					}
				}
			}
			else{
				Toast.makeText(this, getString(R.string.strChooseToChat), Toast.LENGTH_SHORT).show();
			}
			return true;
		default:        
			return super.onOptionsItemSelected(item);
    	}
	 }	    	
	public int deleteGroupContact(int id, String idname){
		int row = getContentResolver().delete(GroupContact.GroupContactColumns.CONTENT_URI, idname + "=" + id, null);
		return row;
	}	
	public String[] getGroupName(){
		Cursor c = getContentResolver().query(Groups.GroupColumns.CONTENT_URI, null, null, null, null);		
		String str = "";
        if (c.moveToFirst()) {        	
			int ColumnFisrt = c.getColumnIndex(Groups.GroupColumns.GROUPNAME);			
			do {
				// Get the field values								
				str += c.getString(ColumnFisrt);
				str +="\n";							
			} while (c.moveToNext());
		}
        String[] res = str.split("\n");
        if(res.length!=0)
        	return res;
        return null;
	}
	public int[] getGroupId(){
		Cursor c = getContentResolver().query(Groups.GroupColumns.CONTENT_URI, null, null, null, null);		
		String str = "";
        if (c.moveToFirst()) {        	
			int ColumnId = c.getColumnIndex(Groups.GroupColumns._ID);			
			do {
				// Get the field values								
				str += (c.getString(ColumnId));
				str +="\n";							
			} while (c.moveToNext());
		}
        int[] res = null;
        if(str.length()>0)str = str.substring(0, str.length()-1);
        if(str.length()!=0){
        	String[] temp = str.split("\n");
        	res = new int[temp.length];		                    
        	for(int i = 0 ; i < res.length ; i++){
        		res[i] = Integer.parseInt(temp[i]);
        	}
        }
		return res;
	}
	public int deleteGroup(int id){
		int row = getContentResolver().delete(Groups.GroupColumns.CONTENT_URI, "_id = " + id, null);
		lsv2 = (ListView)findViewById(R.id.listview2);						
		String[] arrName = getGroupName();
		int[] arrId = getGroupId();
		if(arrId!=null)
			lsv2.setAdapter(new adSimpleText(getApplicationContext(), arrName, arrId));
		else
			lsv2.setAdapter(null);
		return row;
	}
	public Dialog prepareToInsertGroup(final Context context, int idlayout, int idedtext, int btndone, int btnrevert, String pTitle, String pMessage){    	
		final Dialog dialog = new Dialog(context);
    	dialog.setContentView(idlayout);    	
    	dialog.setTitle(pTitle);
    	final EditText edgroupname = (EditText) dialog.findViewById(idedtext);
    	Button btnd = (Button)dialog.findViewById(btndone);
    	btnd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {		
				ContentValues values = new ContentValues();
				values.put(Groups.GroupColumns.GROUPNAME, edgroupname.getText().toString().trim());
				context.getContentResolver().insert(Groups.GroupColumns.CONTENT_URI, values);
				lsv2 = (ListView)findViewById(R.id.listview2);							
				String[] arrName = getGroupName();
				int[] arrId = getGroupId();
				if(arrId!=null)
					lsv2.setAdapter(new adSimpleText(getApplicationContext(), arrName, arrId));
				else
					lsv2.setAdapter(null);
				dialog.cancel();
			}
		});
    	Button btnr = (Button)dialog.findViewById(btnrevert);
    	btnr.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {			
				dialog.cancel();
			}
		});
    	if(pMessage!=null)
    		edgroupname.setText(pMessage);    	
    	return dialog;
    }
	public Dialog prepareToEditGroup(final Context context, int idlayout, int idedtext, int btndone, int btnrevert, String pTitle, String pMessage){    	
		final Dialog dialog = new Dialog(context);
    	dialog.setContentView(idlayout);    	
    	dialog.setTitle(pTitle);
    	final EditText edgroupname = (EditText) dialog.findViewById(idedtext);
    	Button btnd = (Button)dialog.findViewById(btndone);
    	btnd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {		
				ContentValues values = new ContentValues();
				values.put(Groups.GroupColumns.GROUPNAME, edgroupname.getText().toString().trim());
				context.getContentResolver().update(Groups.GroupColumns.CONTENT_URI, values, null, null);
				lsv2 = (ListView)findViewById(R.id.listview2);							
				String[] arrName = getGroupName();
				int[] arrId = getGroupId();
				if(arrId!=null)
					lsv2.setAdapter(new adSimpleText(getApplicationContext(), arrName, arrId));
				else
					lsv2.setAdapter(null);
				dialog.cancel();
			}
		});
    	Button btnr = (Button)dialog.findViewById(btnrevert);
    	btnr.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {			
				dialog.cancel();
			}
		});
    	if(pMessage!=null)
    		edgroupname.setText(pMessage);    	
    	return dialog;
    }
}
